package com.zhoug.speech.xunfei;

import android.content.Context;

import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechRecognizer;

import androidx.annotation.Keep;

/**
 * 讯飞识别器封装
 * @Author 35574
 * @Date 2020/7/8
 * @Description
 */

class XunFeiRecognizer {
    private SpeechRecognizer mRecognizer;
    private RecognizerListener mRecognizerListener;

    public XunFeiRecognizer(Context context) {
        mRecognizer = SpeechRecognizer.createRecognizer(context, new SpeechInitListener(context));
        init();
    }

    /**
     * 初始化配置
     */
    private void init() {
        //设置语法ID和 SUBJECT 为空，以免因之前有语法调用而设置了此参数；或直接清空所有参数，具体可参考 DEMO 的示例。
        mRecognizer.setParameter(SpeechConstant.CLOUD_GRAMMAR, null);
        mRecognizer.setParameter(SpeechConstant.SUBJECT, null);
        // 清空参数
        mRecognizer.setParameter(SpeechConstant.PARAMS, null);
        //设置返回结果格式，目前支持json,xml以及plain 三种格式，其中plain为纯听写文本内容
        mRecognizer.setParameter(SpeechConstant.RESULT_TYPE, "json");
        //此处engineType为“cloud”
        mRecognizer.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);
        //设置语音输入语言，zh_cn为简体中文
        mRecognizer.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
        //设置结果返回语言:方言
        mRecognizer.setParameter(SpeechConstant.ACCENT, "mandarin");
        // 设置语音前端点:静音超时时间，单位ms，即用户多长时间不说话则当做超时处理
        //取值范围{1000～10000}
        mRecognizer.setParameter(SpeechConstant.VAD_BOS, "2000");
        //设置语音后端点:后端点静音检测时间，单位ms，即用户停止说话多长时间内即认为不再输入，
        //自动停止录音，范围{0~10000}
        mRecognizer.setParameter(SpeechConstant.VAD_EOS, "1500");
        //设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点
        mRecognizer.setParameter(SpeechConstant.ASR_PTT, "1");
    }

    /**
     * 设置识别监听器
     * @param recognizerListener
     */
    public void setRecognizerListener(RecognizerListener recognizerListener) {
        this.mRecognizerListener = recognizerListener;
    }

    /**
     * 开始监听语音输入
     * @return false:听写失败 true:成功-开始说话
     */
    public boolean startListening() {
        return mRecognizer.startListening(mRecognizerListener) == ErrorCode.SUCCESS;
    }

    /**
     * 停止监听语音输入,会回掉{@link RecognizerListener#onResult(RecognizerResult, boolean)}
     */
    public void stopListening(){
        mRecognizer.stopListening();
    }

    /**
     * 关闭语音识别,不会回掉RecognizerListener
     */
    public void cancel(){
        mRecognizer.cancel();
    }

    /**
     * 是否正在监听语音输入
     * @return
     */
    public boolean isListener(){
        return mRecognizer.isListening();
    }

    public void destroy(){
        mRecognizer.destroy();
    }

}